package com.dman.multi.cmd;

import java.util.HashMap;
import java.util.Map;

import org.apache.pivot.collections.ArrayList;
import org.apache.pivot.collections.List;
import org.apache.pivot.wtk.TreeView;
import org.apache.pivot.wtk.content.TreeNode;

import com.dman.multi.core.Download;

public class GUIFileTypeCommand implements Command {
	
	private List<Download> downloadList;
	private TreeView treeView;
	private Map<Filter, List<String>> filterToExtension = null;
	
	private enum Filter {
		ALL, MUSIC, VIDEO, PICTURES, PROGRAMS, IMAGES, OTHERS;
	}
	
	public GUIFileTypeCommand(List<Download> downloadList, TreeView treeView) {
		this.downloadList = downloadList;
		this.treeView = treeView;
		filterToExtension = new HashMap<GUIFileTypeCommand.Filter, List<String>>();
		
		List<String> extnList = new ArrayList<String>(".mp3,.ogg,.wav,.flac,.vox,.aiff,.au,.aac,.wma,.ra".split(","));		
		filterToExtension.put(Filter.MUSIC, extnList);
		
		extnList = new ArrayList<String>(".mpg,.mov,.wmv,.avi,.rm,.3gp,.asf,.asx,.bsf,.flv,.divx,.m2p,.m4v,.mkv,.mp4,.mpeg,.ogm,.swf,.wmv,.xvid".split(","));		
		filterToExtension.put(Filter.VIDEO, extnList);
		
		extnList = new ArrayList<String>(".jpg,.jpeg,.tif,.tiff,.png,.gif,.bmp,.svg,.psd".split(","));		
		filterToExtension.put(Filter.PICTURES, extnList);
		
		extnList = new ArrayList<String>(".exe,.com,.msi,.rpm,.deb,.bin,.sh,.ksh,.csh".split(","));		
		filterToExtension.put(Filter.PROGRAMS, extnList);
		
		extnList = new ArrayList<String>(".iso,.img,.dmg,.uif,.vmdk".split(","));		
		filterToExtension.put(Filter.IMAGES, extnList);
	}

	@Override
	public void execute() {
		// get tree node and corresponding filter
		TreeNode tn = (TreeNode) treeView.getSelectedNode();
		String text = tn.getText().toUpperCase();
		Filter filterType = Filter.valueOf(text);
		List<String> extnList = null;

		// get the extn list if applicable
		if(filterType != Filter.ALL)
			extnList = filterToExtension.get(filterType);
		
		// iterate through extension list and find if the download has to be visible
		String fileName = "";
		synchronized (downloadList) {
			for(Download d: downloadList){
				fileName = d.getFileName();
				d.setVisible(true);
				if(filterType != Filter.ALL){
					d.setVisible(false);
					for(String extn: extnList){
						if(fileName.endsWith(extn)){
							d.setVisible(true);
							break;
						}
					}
				}
			}
		}
	}

}
